Библиотеки и данные
library(dplyr)
##
## Присоединяю пакет: 'dplyr'
## Следующие объекты скрыты от 'package:stats':
##
## filter, lag
## Следующие объекты скрыты от 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
library(ggpubr)
library(corrplot)
## corrplot 0.92 loaded
library(plotly)
##
## Присоединяю пакет: 'plotly'
## Следующий объект скрыт от 'package:ggplot2':
##
## last_plot
## Следующий объект скрыт от 'package:stats':
##
## filter
## Следующий объект скрыт от 'package:graphics':
##
## layout
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
library(pheatmap)
ins_data <- read.csv('C:/Users/Lenovo/Desktop/Настя/Биостатистика/Визуализация биомед данных (Дмитрий Серебренников)/ДЗ 2/insurance_cost.csv', stringsAsFactors = T)
Сделайте интерактивный plotly график отношения индекса массы тела и трат на страховку. Раскрасьте его по колонке smoker
plot_ly(data = ins_data[(ins_data$bmi != 0) & (ins_data$charges != 0),],
x = ~ bmi,
y = ~ charges,
color= ~smoker )
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
## Setting the mode to markers
## Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
Сделайте тоже самое через ggplotly
plot_1 <- ins_data %>%
filter(bmi != 0 & charges != 0) %>%
ggplot(aes(x=bmi, y=charges, color = smoker)) +
geom_point() +
theme_minimal()
ggplotly(plot_1)
Кратко сделайте корреляционный анализ данных insurance_cost. Посмотрите документацию пакетов, которые мы проходили на занятии и, исходя из этого, постройте минимум два новых типа графика (которые мы не строили на занятии).
ins_clear <- ins_data %>%
filter(age != 0 & bmi != 0 & children != 0 & charges != 0) %>%
select(is.integer | is.numeric) # чистые данные
## Warning: Use of bare predicate functions was deprecated in tidyselect 1.1.0.
## ℹ Please use wrap predicates in `where()` instead.
## # Was:
## data %>% select(is.integer)
##
## # Now:
## data %>% select(where(is.integer))
## Warning: Use of bare predicate functions was deprecated in tidyselect 1.1.0.
## ℹ Please use wrap predicates in `where()` instead.
## # Was:
## data %>% select(is.numeric)
##
## # Now:
## data %>% select(where(is.numeric))
ins_cor <- cor(ins_clear) # корреляционная матрица
corrplot(ins_cor, method = 'color')
corrplot(ins_cor, method = 'circle')
corrplot(ins_cor, method = 'ellipse')
corrplot(ins_cor, method = 'pie')
Превратите все номинативные переменные в бинарные/дамми. Т.е. sex и smoker должны стать бинарными (1/0), а каждое уникальное значение region – отдельной колонкой, где 1 говорит о наличии этого признака для наблюдения, а 0 – об отсутствии. Создайте новый датафрейм, где вы оставите только нумерические переменные.
ins_bin <- ins_data %>%
mutate(`smoker`=ifelse(`smoker` == "no", 0, 1) %>% as.factor(), `sex`=ifelse(`sex` == "male", 1, 0) %>% as.factor(), `southwest` = ifelse(`region` == "southwest", 1, 0) %>% as.factor() , `southeast`= ifelse(`region` == "southeast", 1, 0) %>% as.factor() , `northwest`= ifelse(`region` == "northwest", 1, 0) %>% as.factor() ,`northeast`= ifelse(`region` == "northeast", 1, 0) %>% as.factor() , `region` = NULL)
ins_num <- ins_bin %>% select(where(is.numeric))
Постройте иерархическую кластеризацию на этом датафрейме
ins_scaled <- scale(ins_num)
ins_dist <- dist(ins_scaled, method = "euclidean")
#as.matrix(ins_dist)[1:5,1:5]
ins_hc <- hclust(d = ins_dist,
method = "ward.D2")
fviz_dend(ins_hc,
cex = 0.1)
## Warning: `guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> =
## "none")` instead.
Сделайте одновременный график heatmap и иерархической кластеризации
pheatmap(ins_scaled)
Используя документацию или предложенный учебник сделайте ещё несколько возможных графиков по иерархической кластеризации. Попробуйте раскрасить кластеры разными цветами.
ins_hc_mcquitty <- hclust(d = ins_dist,
method = "mcquitty")
fviz_dend(ins_hc_mcquitty,
k = 4,
k_colors = c("#2E9FDF", "#00AFBB", "#E7B800", "#FC4E07"),
color_labels_by_k = TRUE,
cex = 0.1)
## Warning: `guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> =
## "none")` instead.
ins_hc_average <- hclust(d = ins_dist,
method = "average")
fviz_dend(ins_hc_average,
k = 3,
k_colors = c("#2E9FDF", "#E7B800","#FC4E07"),
color_labels_by_k = TRUE,
cex = 0.1)
## Warning: `guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> =
## "none")` instead.